var readline = require('readline');
var db = require('./db.json');
db.verbs = require('./verbs.json');

//Keep track of state of chatbot
//Can gather user input like name, location, color, etc...
var randCount = 0;

var rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

console.log("Psychologist ready, \n(type 'exit' to end session)");
rl.on("line", function(userInput){
	input = userInput.toLowerCase();
	input = input.trim();
	if(input === "exit"){
		exit();
	}
	else {
		handleInput(input);
	}
});

function exit() {
	if(query(db.patient, "name") !== ""){
		console.log("Goodbye " + db.patient.info.name + "!");
	} else {
		console.log("Goodbye!");
	}
	rl.close();
}

function handleInput(input) {
	var response;
	//parse keys for db
	var subject = parseSubject(input);
	var verb = parseVerb(input);
	var topic;
	if(verb){
		topic = parseTopic(verb, input);
		//console.log("subject:", subject,",", "verb == ", verb,",", "topic == ", topic);
	}
	if(topic){
		//save user info
		saveUserInput(subject, verb, topic, input);
		response = gatherDBResponse(topic, verb);
	}
	if(!response)
		response = gatherResponse(input);
	console.log(response);
}




                                                                                                                                                                
//88888888ba                                                     88888888888                                             88                                       
//88      "8b                                                    88                                               ,d     ""                                       
//88      ,8P                                                    88                                               88                                              
//88aaaaaa8P'  ,adPPYYba,  8b,dPPYba,  ,adPPYba,   ,adPPYba,     88aaaaa  88       88  8b,dPPYba,    ,adPPYba,  MM88MMM  88   ,adPPYba,   8b,dPPYba,   ,adPPYba,  
//88""""""'    ""     `Y8  88P'   "Y8  I8[    ""  a8P_____88     88"""""  88       88  88P'   `"8a  a8"     ""    88     88  a8"     "8a  88P'   `"8a  I8[    ""  
//88           ,adPPPPP88  88           `"Y8ba,   8PP"""""""     88       88       88  88       88  8b            88     88  8b       d8  88       88   `"Y8ba,   
//88           88,    ,88  88          aa    ]8I  "8b,   ,aa     88       "8a,   ,a88  88       88  "8a,   ,aa    88,    88  "8a,   ,a8"  88       88  aa    ]8I  
//88           `"8bbdP"Y8  88          `"YbbdP"'   `"Ybbd8"'     88        `"YbbdP'Y8  88       88   `"Ybbd8"'    "Y888  88   `"YbbdP"'   88       88  `"YbbdP"'  
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


function parseSubject(input){
	var subject;
	if(input.match(/^i /) || input.match(/ i /) || input.match(/ i/) && !input.match(/ i./) || input.match(/i'm /) || input.match(/im /) && ! input.match(/.im /) || input.match(/ i am/) || input.match(/i am /) && !input.match(/.i am /)){
		subject = "i";
	}
	else if(input.match(/^my /) || input.match(/ my /)){
		var thing = input.substring(input.indexOf("my")+3);
		subject = "my " + thing;
	}
	else if(input.match(/ me /) || input.match(/ me/) && !input.match(/ me./)){
		subject = "me";
	}
	else if(input.match(/^your /) || input.match(/ your /) || input.match(/ your/) && !input.match(/ your./)){
		var thing = input.substring(input.indexOf("your")+3);
		subject = "your " + thing;
	}
	else if(input.match(/^you /) || input.match(/ you /) || input.match(/ you/) && !input.match(/ you./)){
		subject = "you"
	}
	else if(input.match(/^we/) || input.match(/ we /) || input.match(/ we/) && !input.match(/ we./)){
		subject = "we";
	}
	else if(input.match(/^our/) || input.match(/ our /) || input.match(/ our/) && !input.match(/ our./)){
		var thing = input.substring(input.indexOf("our")+3);
		subject = "our " + thing;
	}
	return subject;
}

function parseVerb (input) {
	input = input.split(" ");
	for(var i = 0; i < input.length; i++){
		if(isVerb(db.verbs, input[i])){
			return input[i];
		}
	}
}

function parseTopic (verb, input) {
	var topic = input.slice(input.indexOf(verb)+ verb.length);
	return topic.trim();
}

function respond (argument) {
	// body...
}

function gatherResponse(input){
	var response;
	if(input.match(/^i /) || input.match(/ i /) || input.match(/i'm/) || input.match(/i am/)){
		response = iFindVerb(input);
	}
	else if(input.match(/^my /) || input.match(/ my /)){
		response = myFindVerb(input);
	}
	else if(input.match(/ me /)){
		response = randomMessage();
	}
	else if(input.match(/^your /) || input.match(/ your /)){
		response = randomMessage();
	}
	else if(input.match(/^you /) || input.match(/ you/)){
		response = uFindVerb(input)
	}
	else if(input.match(/^we/) || input.match(/ we /)){
		response = iFindVerb(input);
	}
	else if(input.match(/^our/) || input.match(/ our /)){
		response = randomMessage();
	}else if(input.match(/what /) || input.match(/where /) || input.match(/when /) || input.match(/who /) || input.match(/why /) || input.match(/how /)){
		response = "I don't know";
	}else{
		response = randomMessage();
	}
	return response;
}

function iFindVerb(input){
	var message;
	var d = new Date().getMilliseconds();
	if(input.match(/don't like/)){
		//database
		d = d % 4;
		if(d == 0){
			message = "Why don't you " + input.slice(input.indexOf("like")) + "?";
		}else if(d == 1){
			message = "Tell me more";
		}else if(d == 2){
			message = "Why do you feel that way?";
		}else{
			message = "What do you like?"
		}
	} else if(input.match(/ like /)){
		//database
		d = d % 4;
		if(d == 0){
			message = "Why do you " + input.slice(input.indexOf("like")) + "?";
		}else if(d == 1){
			message = "Tell me more";
		}else if(d == 2){
			message = "Why do you feel that way?";
		}else{
			message = "What else do you like?"
		}
	} else if(input.match(/don't want/)){
		d = d % 2;
		if(d == 0){
			message = "Why don't you " + input.slice(input.indexOf("want")) + "?";
		}else{
			message = "Tell me more";
		}
	} else if(input.match(/want/)){
		//database
		d = d % 2;
		if(d == 0){
			message = "Why do you " + input.slice(input.indexOf("want")) + "?";
		}else{
			message = "Tell me more";
		}
	} else if(input.match(/can not/) || input.match(/can't/)){
		d = d % 2;
		if((d == 0) && (input.match(/can not/))){
			message = "Why can't you" + input.slice(input.indexOf("not") + 3) + "?";
		}else if((d == 0) && (input.match(/can't/))){
			message = "Why can't you" + input.slice(input.indexOf("can't") + 5) + "?";
		}else{
			message = "Tell me more";
		}
	}else if(input.match(/i'm/) || input.match(/i am/) || input.match(/im/)|| input.match(/we are/) || input.match(/we're/)){
		//check for positive emotion
		if(input.match(/happy/) || input.match(/excited/) || input.match(/good/)){
			d = d % 3;
			db.patient.info.emotion = input.slice(input.indexOf("m ") + 2);
			if(d == 0){
				message = "Why are you" + input.slice(input.indexOf("m ") + 2) + "?";
			}else if(d == 1){
				message = "Why do you feel that way?";
			}else{
				message = "Tell me more";
			}
		}else if(input.match(/sad/) || input.match(/upset/)){
		//check for negative emotion
			d = d % 3;
			db.patient.info.emotion = input.slice(input.indexOf("m ") + 2);
			if(d == 0){
				message = "Why are you" + input.slice(input.indexOf("m") + 1) + "?";
			}else if(d == 1){
				message = "Why do you feel that way?";
			}else if(d == 2){
				message = "What is wrong?"
			}else{
				message = "Tell me more";
			}
		}else if(input.match(/ a /)){
			d = d % 3;
			if(d == 0){
				message = "Why are you " + input.slice(input.indexOf("a ")) + "?";
			}else if((d == 1)){
				message = "Why do you feel that way?";
			}else{
				message = "Tell me more";
			}
		}else if(input.match(/ in /)){
		//could use database "in school"
			d = d % 1;
			if(d == 0){
				message = "How is it " + input.slice(input.indexOf("in ")) + "?";
			}
		}else if(input.match(/ young /)){
			d = d % 1;
			if(d == 0){
				message = "Tell me more";
			}
		}else{
			message = randomMessage();
		}
	}else if(input.match(/ need /)){
		d = d % 2;
		if(d == 0){
			message = "Why do you " + input.slice(input.indexOf("need")) + "?";
		}else if((d == 1)){
			message = "Tell me more";
		}
	}else if(input.match(/ wakeup /)){
		d = d % 2;
		if(d == 0){
			message = "Why do you " + input.slice(input.indexOf("wakeup")) + "?";
		}else if((d == 1)){
			message = "Tell me more";
		}
	}else if(input.match(/ sleep /)){
		d = d % 2;
		if(d == 0){
			message = "Why do you " + input.slice(input.indexOf("sleep")) + "?";
		}else if((d == 1)){
			message = "Tell me more";
		}
	}else if(input.match(/ got a /)){
		d = d % 3;
		if(d == 0){
			message = "How did you get" + input.slice(input.indexOf(" a ")) + "?";
		}else if((d == 1)){
			message = "How is your " + input.slice(input.indexOf("got a") + 5) + "?";
		}else if((d == 2)){
			message = "Tell me more";
		}
	}else{
		message = randomMessage();
	}
	return message;
}

function myFindVerb(input){
	var message;
	var d = new Date().getMilliseconds();
	if(input.match(/dog died/)){
		d = d % 3;
		if(d == 0){
			message = "I'm sorry, how did your dog die?";
		}else if((d == 1)){
			message = "What happened?";
		}else if((d == 2)){
			message = "Tell me more";
		}
	}
	else
		message = "i dont understand";
	return message;
}

function uFindVerb(input){
	var message;
	var d = new Date().getMilliseconds();
	if(input.match(/what /) || input.match(/where /) || input.match(/when /) || input.match(/who /) || input.match(/why /) || input.match(/how /)){
		if(input.match(/you smart/)){
			message = "I'm a doctor";
		} else {
			message = "Ignore the man behind the curtain";
		}
	} else {
		message = randomMessage();
	}
	return message;
}

function getName(callback){
	var message;
	rl.question('What is your name?', function(answer) {
		if(answer === "exit"){
			exit();
		}else {
			if(answer.match("name is")){
				db.patient.info.name = answer.slice(answer.indexOf("name is ") + 8);
			} else if (answer.match(/'m /) || answer.match(/ am /) || answer.match(/m /)){
				db.patient.info.name = answer.slice(answer.indexOf("m ") + 2);
			} else {
				db.patient.info.name = answer;
			}
			console.log('Hello ' + db.patient.info.name);
		}
	});
	return "";
}

function getColor(callback){
	var message;
	rl.question('What is your favorite color?', function(answer) {
		if(answer === "exit"){
			exit();
		}
		else if(answer.match(/my favorite color is/)){
			db.patient.info.color = answer.slice(answer.indexOf(" is") + 4);
			console.log(db.patient.info.color + " is a nice color");
		}
		else {
			console.log(answer + " is a nice color");
			db.patient.info.color = answer;
		}
	});
	return "";
}

function getFeeling(callback){
	var message;
	rl.question('How are you?', function(answer) {
		if(answer === "exit"){
			exit();
		} else {
			if(answer.match(/'m /) || answer.match(/ am /) || answer.match(/m /)){
				db.patient.info.emotion = answer.slice(answer.indexOf("m ") + 2);
			} else {
				db.patient.info.emotion = answer;
			}
			console.log("Tell me more");
		}
	});
	return "";
}

function getLocation(callback){
	var message;
	rl.question('Where did you live before you came here?', function(answer) {
		if(answer === "exit"){
			exit();
		}
		else if(answer.match(/lived in/)){
			db.patient.info.location = answer.substring(answer.indexOf("in")+3);
			rl.question('How did you like it in ' + db.patient.info.location + "?\n", function(answer) {
				if(answer === "exit"){
					exit();
				} else {
					console.log("Tell me more");
				}
			});
		}
		else {
			db.patient.info.location = answer;
			rl.question('How did you like it in ' + answer + "?\n", function(answer) {
				if(answer === "exit"){
					exit();
				} else {
					console.log("Tell me more");
				}
			});
		}
	});
	return "";
}

function randomMessage(){
	var d = randCount;
	
	var message;
	//check database for good response
	message = respondFromHistory();
	if(message){
		return message;
	}
	message = respondFromInputTopics();
	if(message){
		return message;
	}

	randCount++;
	if(d == 0){
		message = getName();
	}else if(d == 1){
		message = getColor();
	}else if(d == 2){
		if(query(db.patient, "emotion") !== ""){
			message = randomMessage();
		}
		else
			message = getFeeling();
	}else if(d == 3){
		message = getLocation();
	}else if(d == 4){
		message = "Do you like computer programming?";
	}else if(d == 5){
		message = "How does playing checkers make you feel?";
	}else if(d == 6){
		message = "Are you beautiful?";
	}else if(d == 7){
		message = "Where are your family?";
	}else if(d == 8){
		message = "Why do you always wear those sun glasses?";
	}else if(d == 9){
		message = "Tell me more about " + db.patient.info.location;
	}else if(d == 10){
		message = "Where did you get the name "+ db.patient.info.name;
	}
	else{
		message = respondFromDBTopics();
		if(message){
			return message;
		}
		message = "Tell me more";
	}
	return message;
}



//888888ba,    88888888ba      88888888888                                             88                                       
//8      `"8b   88      "8b     88                                               ,d     ""                                       
//8        `8b  88      ,8P     88                                               88                                              
//8         88  88aaaaaa8P'     88aaaaa  88       88  8b,dPPYba,    ,adPPYba,  MM88MMM  88   ,adPPYba,   8b,dPPYba,   ,adPPYba,  
//8         88  88""""""8b,     88"""""  88       88  88P'   `"8a  a8"     ""    88     88  a8"     "8a  88P'   `"8a  I8[    ""  
//8         8P  88      `8b     88       88       88  88       88  8b            88     88  8b       d8  88       88   `"Y8ba,   
//8      .a8P   88      a8P     88       "8a,   ,a88  88       88  "8a,   ,aa    88,    88  "8a,   ,a8"  88       88  aa    ]8I  
//888888Y"'     88888888P"      88        `"YbbdP'Y8  88       88   `"Ybbd8"'    "Y888  88   `"YbbdP"'   88       88  `"YbbdP"' 


function isVerb(db, verb){
	var letter = verb.charAt(0);
	for(x in db[letter]){
		if(db[letter][x] === verb){
			return true;
		}
	}
	return false
}

function query(db, searchItem) {
	for(var topic in db){
		for(var item in db[topic]){
			if(item === searchItem){
				return db[topic][item];
			}
		}
	}
}

function queryRelatedTopic(db, searchItem) {
	var allRelTopics;
	for(var topic in db){
		for(var item in db[topic]){
			if(item === searchItem){
				allRelTopics = db[topic];
			}
		}
	}
	var relTopics={};
	for(var topic in allRelTopics){
		if(topic !== searchItem){
			relTopics[topic]= allRelTopics[topic];
		}
	}
	return relTopics;
}

function randomItem(obj){
	var count = 0;
	var i = Math.floor(Math.random()*Object.size(obj));
	for (x in obj){
		if(count === i){
			return x;
		}
		count++;
	}
}

Object.size = function(obj) {
    var size = 0, key;
    for (key in obj) {
        if (obj.hasOwnProperty(key)) size++;
    }
    return size;
};

function saveUserInput(subject, verb, topic, userInput){
	//store input object
	var input = {
		"subject": subject,
		"verb": verb,
		"topic": topic,
		"input": userInput,
		"visited": false
	}
	db.patient.input.push(input);
	db.inputTopics.push({"topic": topic, "verb": verb, visited: false});
}

function gatherDBResponse(topic, verb){
	var subTopic = query(db.topics, topic);
	if(subTopic && Object.size(subTopic) > 0){
		return subTopic[randomItem(subTopic)];
	}
	else{
		var relTopics = queryRelatedTopic(db.topics, topic)
		if(relTopics && Object.size(relTopics) > 0){
			if(verb === "like")
				return "do you like " + randomItem(relTopics);
			else{
				return "do you " + verb + " " + randomItem(relTopics) + " too";
			}
		}
		else
			return null;
	}
}

function respondFromHistory(){
	var response;
	for (var i = db.patient.input.length - 1; i >= 0; i--) {
		if(!db.patient.input[i].visited){
			db.patient.input[i].visited = true;
			response = gatherDBResponse(db.patient.input[i].topic, db.patient.input[i].verb);
			return response
		}
	}
}

function respondFromInputTopics(){
	/*var topic;
	var verb;
	for (var i = db.inputTopics.length - 1; i >= 0; i--) {
		if(!db.inputTopics[i].visited){
			db.inputTopics[i].visited = true;
			topic = db.inputTopics[i].topic;
			verb = db.inputTopics[i].verb;
			break
		}
	}
	if(topic && topic.split(" ").length === 1){
		var response = "tell me more about " + verb + "ing "+ topic
		return response.replace("eing", )
	}
	else*/
		return null;
}

function respondFromDBTopics(){
	var topic;
	topic = randomItem(db.topics);
	if(topic && !db.topics[topic].visited){
		db.topics[topic].visited = true;
		return "how do " + topic + " make you feel";
	}
	else
		return null
}

/*
{
	"psychologist_input": [
	!	"I'm upset",
	!	"my dog died",
	!	"I got a job",
	!	"I'm happy",
	!	"I need help",
	!	"I dont like TV",
	!	"I like volleyball",
	!	"I am in school",
	!	"I can not sleep well",
	!	"I sleep late",
	!	"I wakeup early",
	!	"I like classical music",
	!	"I'm a bad person",
	!	"I dont want to be here",
	!	"what makes you smart",
	!	"I am young"
	],
	"patient_input": [
	!	"what is wrong",
	!	"tell me more",
	!	"Why do you feel that way",
	!	"how are you",
	!	"do you like computer programming",
	!	"Why do you always wear those sun glasses",
	!	"What is your favorite color",
	!	"What is your name",
	!	"how does playing checkers make you feel",
		"how did your illness make you feel",
	!	"are you beautiful",
	!	"Where are your family",
	!	"where did you live before you came here",
		"When did you lose it",
	!	"what happened",
	!	"I'm a doctor"
	]
}*/